
package com.dy.db;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import com.dy.config.CreatConfig;
import com.dy.config.MysqlConfig;
import com.dy.model.ClassAndPackage;
import com.dy.model.TableInfo;
import com.dy.net.MysqlTableInfo;
import com.dy.run.CreatManager;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @Description:
 * @Date：2017年12月25日 @author： DongY
 * @version ：1.0 1.[2017年12月25日]CreatBy：dy
 */
@Mojo(name = "creat", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class Creat extends AbstractMojo {
	/**
	 * 读取配置文件的路径. 注解内容property说明 允许让用户在命令行通过-D指定属性值<在这里通过-D
	 * creat.packageFile指定文件路径 >
	 */
	@Parameter(property = "creat.packageFile", defaultValue = "${project.basedir}/src/main/resources/creatCfg.json", required = true)
	private File creatCfg;
	@Parameter(property = "creat.dbJsonFile", defaultValue = "${project.basedir}/src/main/resources/msqlConfig.json", required = true)
	private File msqlConfig;
	@Parameter(defaultValue = "${basedir}")
	private String baseDir;
	@Parameter(defaultValue = "${basedir}/src/main/java/")
	private String classBaseDir;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		if (msqlConfig == null) {
			throw new RuntimeException("未找到数据库配置信息");
		}
		if (creatCfg == null) {
			throw new RuntimeException("包信息配置文件未找到");
		}
		final ObjectMapper oMapper = new ObjectMapper();
		try {
			final MysqlConfig mysqlConfig = oMapper.readValue(msqlConfig, MysqlConfig.class);
			final CreatConfig config = oMapper.readValue(creatCfg, CreatConfig.class);
			final MysqlTableInfo mysqlTableInfo = new MysqlTableInfo();
			final TableInfo tableInfo = mysqlTableInfo.getTableInfos(mysqlConfig, config);
			final ClassAndPackage classAndPackage = new ClassAndPackage(config, tableInfo);
			CreatManager.baseDir = baseDir;
			final CreatManager manager = new CreatManager(tableInfo, classAndPackage);
			manager.docreat();
		} catch (final IOException e) {

			e.printStackTrace();
		} catch (final ClassNotFoundException e) {

			e.printStackTrace();
		} catch (final SQLException e) {

			e.printStackTrace();
		} catch (final InstantiationException e) {

			e.printStackTrace();
		} catch (final IllegalAccessException e) {

			e.printStackTrace();
		}

	}

}
